export default {
  namespaced: true,
  state: {
    shopCatList: [],
    resultShopList: [],
    subtotal: 0,
  },
  getters: {},
  mutations: {
    append(state, shopItem) {
      let index = state.shopCatList.indexOf(shopItem);
      if (index != -1) {
        state.shopCatList[index].count++;

        state.shopCatList[index]["subtotal"] =
          state.shopCatList[index]["price"] * state.shopCatList[index]["count"];
        state.subtotal += state.shopCatList[index].price - 0;
      } else {
        shopItem["id"] = state.shopCatList.length;
        shopItem["count"] = 1;
        shopItem["subtotal"] = shopItem["price"] * shopItem["count"];
        state.subtotal += shopItem["price"] * shopItem["count"];
        state.shopCatList.unshift(shopItem);
      }
    },
    get(state, shopItem) {
      for (let item of state.shopCatList) {
        if (item.name === shopItem.shopItem.name) {
          shopItem.callback(item);
          return;
        }
      }
      shopItem.callback(false);
    },
    add(state, item) {
      let index = state.shopCatList.indexOf(item);
      state.shopCatList[index].count++;
      // 改变小计
      state.shopCatList[index].subtotal =
        state.shopCatList[index].count * state.shopCatList[index].price;
      // 改变总计
      state.subtotal += state.shopCatList[index].price - 0;
    },
    minus(state, item) {
      let index = state.shopCatList.indexOf(item);
      if (state.shopCatList[index].count > 1) {
        state.shopCatList[index].count--;
        // 改变小计
        state.shopCatList[index].subtotal =
          state.shopCatList[index].count * state.shopCatList[index].price;
        // 改变总计
        state.subtotal -= state.shopCatList[index].price;
      } else {
        state.subtotal -= state.shopCatList[index].price;
        state.shopCatList.splice(index, 1);
      }
    },
    clear(state) {
      state.shopCatList.splice(0, state.shopCatList.length);
      state.subtotal = 0;
    },
    addResultShopList(state, arr) {
      state.resultShopList.unshift(...arr);
    },
  },
  actions: {},
};
